<template>
  <div class="create-post">
    <div class="post-form card">
      <div class="form-header">
        <h2>发布新帖子</h2>
        <p>分享你的校园生活</p>
      </div>

      <el-form
        ref="formRef"
        :model="postForm"
        :rules="rules"
        label-width="80px"
        size="large"
      >
        <el-form-item label="标题" prop="title">
          <el-input
            v-model="postForm.title"
            placeholder="请输入帖子标题"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="分类" prop="categoryId">
          <el-select
            v-model="postForm.categoryId"
            placeholder="请选择分类"
            style="width: 200px"
          >
            <el-option
              v-for="category in categories"
              :key="category.id"
              :label="category.name"
              :value="category.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="内容" prop="content">
          <el-input
            v-model="postForm.content"
            type="textarea"
            placeholder="分享你的想法..."
            :rows="8"
            maxlength="5000"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="图片">
          <div class="upload-section">
            <el-upload
              ref="uploadRef"
              action="/api/file/upload"
              :headers="uploadHeaders"
              list-type="picture-card"
              :on-success="handleUploadSuccess"
              :on-remove="handleRemoveImage"
              :before-upload="beforeUpload"
              :file-list="fileList"
              accept="image/*"
              multiple
              :limit="5"
            >
              <el-icon><Plus /></el-icon>
            </el-upload>
            <div class="upload-tip">
              支持jpg、png、gif格式，最多5张图片，每张不超过10MB
            </div>
          </div>
        </el-form-item>

        <el-form-item>
          <div class="form-actions">
            <el-button @click="goBack">取消</el-button>
            <el-button
              type="primary"
              :loading="loading"
              @click="handleSubmit"
            >
              {{ loading ? '发布中...' : '发布帖子' }}
            </el-button>
          </div>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { createPost } from '@/api/post'
import { ElMessage } from 'element-plus'
import Cookies from 'js-cookie'

const router = useRouter()
const formRef = ref()
const uploadRef = ref()
const loading = ref(false)
const fileList = ref([])

// 表单数据
const postForm = reactive({
  title: '',
  content: '',
  categoryId: null,
  images: []
})

// 分类数据
const categories = ref([
  { id: 1, name: '学习交流' },
  { id: 2, name: '生活分享' },
  { id: 3, name: '求助提问' },
  { id: 4, name: '社团活动' },
  { id: 5, name: '二手交易' }
])

// 上传请求头
const uploadHeaders = {
  Authorization: `Bearer ${Cookies.get('token')}`
}

// 验证规则
const rules = {
  title: [
    { required: true, message: '请输入标题', trigger: 'blur' },
    { min: 5, max: 100, message: '标题长度在 5 到 100 个字符', trigger: 'blur' }
  ],
  categoryId: [
    { required: true, message: '请选择分类', trigger: 'change' }
  ],
  content: [
    { required: true, message: '请输入内容', trigger: 'blur' },
    { min: 10, max: 5000, message: '内容长度在 10 到 5000 个字符', trigger: 'blur' }
  ]
}

// 上传前验证
const beforeUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt10M = file.size / 1024 / 1024 < 10

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt10M) {
    ElMessage.error('图片大小不能超过 10MB!')
    return false
  }
  return true
}

// 上传成功回调
const handleUploadSuccess = (response, file, fileList) => {
  if (response.code === 200) {
    postForm.images.push(response.data.fileName)
    ElMessage.success('图片上传成功')
  } else {
    ElMessage.error('图片上传失败')
  }
}

// 移除图片
const handleRemoveImage = (file, fileList) => {
  if (file.response && file.response.code === 200) {
    const fileName = file.response.data.fileName
    const index = postForm.images.indexOf(fileName)
    if (index > -1) {
      postForm.images.splice(index, 1)
    }
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    loading.value = true
    
    const response = await createPost(postForm)
    
    if (response.code === 200) {
      ElMessage.success('发布成功！')
      router.push(`/post/${response.data.id}`)
    } else {
      ElMessage.error(response.message || '发布失败')
    }
  } catch (error) {
    console.error('发布失败:', error)
    ElMessage.error('发布失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 返回上一页
const goBack = () => {
  router.back()
}
</script>

<style scoped>
.create-post {
  max-width: 800px;
  margin: 0 auto;
}

.form-header {
  text-align: center;
  margin-bottom: 30px;
}

.form-header h2 {
  color: #303133;
  margin-bottom: 8px;
}

.form-header p {
  color: #909399;
}

.upload-section {
  width: 100%;
}

.upload-tip {
  margin-top: 8px;
  font-size: 12px;
  color: #909399;
}

.form-actions {
  display: flex;
  justify-content: center;
  gap: 16px;
}

:deep(.el-upload--picture-card) {
  width: 100px;
  height: 100px;
}

:deep(.el-upload-list--picture-card .el-upload-list__item) {
  width: 100px;
  height: 100px;
}
</style>